package com.jinzhi.jzweb.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * 应聘记录
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/applicationRecord")
public class ApplicationRecordController extends BaseController {
    @Autowired
    private ApplicationRecordService applicationRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private RecruitmentNewsService recruitmentNewsService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private DictService dictService;


    @GetMapping()
    @RequiresPermissions("jzweb:applicationRecord:applicationRecord")
    String ApplicationRecord() {
        return "jzweb/applicationRecord/applicationRecord";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:applicationRecord:applicationRecord")
    public Result<Page<ApplicationRecordDO>> list(ApplicationRecordDO applicationRecordDTO) {
        Wrapper<ApplicationRecordDO> wrapper = new EntityWrapper<ApplicationRecordDO>().orderBy("id", false);
        if (applicationRecordDTO.getState() != null){
            wrapper.eq("state",applicationRecordDTO.getState());
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(applicationRecordDTO.getUserName())){
            Wrapper<UserDO> Wrapper = new EntityWrapper<UserDO>().like("name",applicationRecordDTO.getUserName());
            List<UserDO>  userDOS = userService.selectList(Wrapper);
            String str = "";
            for (UserDO userDO : userDOS){
                str = str + userDO.getId() + ",";
            }
            wrapper.and();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
                wrapper.in("user_id",str.substring(0,str.length()-1));
            }else{
                wrapper.eq("user_id",null);
            }
        }
        if (StringUtils.isNotBlank(applicationRecordDTO.getRnewsName())){
            Wrapper<RecruitmentNewsDO> reWrapper = new EntityWrapper<RecruitmentNewsDO>().like("name",applicationRecordDTO.getRnewsName());
            List<RecruitmentNewsDO>  recruitmentNewsDOS = recruitmentNewsService.selectList(reWrapper);
            String str = "";
            for (RecruitmentNewsDO recruitmentNewsDO : recruitmentNewsDOS){
                str = str + recruitmentNewsDO.getId() + ",";
            }
            wrapper.and();
            if(StringUtils.isNotBlank(str)){
                wrapper.in("rnews_id",str.substring(0,str.length()-1));
            }else{
                wrapper.eq("rnews_id",null);
            }
        }

        String roleName = getRoleNames();//查询用户角色
        if (!roleName.contains("超级用户角色")) {
            wrapper.eq("org_id",this.getUser().getOrgId());
        }else {
            if (StringUtils.isNotBlank(applicationRecordDTO.getOrgName())){
                Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",applicationRecordDTO.getOrgName());
                List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
                String str = "";
                for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
                    str = str + organizationNewsDO.getId() + ",";
                }
                wrapper.and();
                if(StringUtils.isNotBlank(str)){
                    wrapper.in("org_id",str.substring(0,str.length()-1));
                }else{
                    wrapper.eq("org_id",null);
                }
            }
        }

        Page<ApplicationRecordDO> page = applicationRecordService.selectPage(getPage(ApplicationRecordDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ApplicationRecordDO obj = (ApplicationRecordDO) page.getRecords().get(i);
            if (obj.getUserId() != null){
                UserDO userDO = userService.selectById(obj.getUserId());
                if (userDO != null) {
                    if(userDO.getName()==null){
                        obj.setUserName(userDO.getUsername());
                    }else {

                    }  obj.setUserName(userDO.getName());

                }
            }
            if (obj.getOrgId() != null){
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                }
            }
            if (obj.getRnewsId() != null){
                RecruitmentNewsDO recruitmentNewsDO = recruitmentNewsService.selectById(obj.getRnewsId());
                if (recruitmentNewsDO != null) {
                    obj.setRnewsName(recruitmentNewsDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:applicationRecord:add")
    String add() {
        return "jzweb/applicationRecord/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:applicationRecord:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        ApplicationRecordDO applicationRecord = applicationRecordService.selectById(id);
        model.addAttribute("applicationRecord", applicationRecord);
        return "jzweb/applicationRecord/edit";
    }

    @GetMapping("/info/{id}")
    @RequiresPermissions("jzweb:applicationRecord:applicationRecord")
    String info(@PathVariable("id") Long id, Model model) {
        ApplicationRecordDO applicationRecord = applicationRecordService.selectById(id);
        ResumesDO resumes = resumesService.findOneByKv("user_id", applicationRecord.getUserId());
        if (resumes.getUserId() != null) {
            UserDO userDO = userService.selectById(resumes.getUserId());
            if (userDO != null) {
                resumes.setUserName(userDO.getUsername());
                resumes.setMobile(userDO.getMobile());
                resumes.setSex(userDO.getSex());
                resumes.setHeadPortrait(userDO.getHeadPortrait());
                resumes.setPoliticalAffiliation(userDO.getPoliticalAffiliation());
                resumes.setLiveAddress(userDO.getLiveAddress());
                resumes.setEmail(userDO.getEmail());
                resumes.setDateOfBirth(userDO.getDateOfBirth());
            }
        }
        model.addAttribute("resumes", resumes);
        return "jzweb/resumes/info";
    }

    @Log("添加应聘记录")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:applicationRecord:add")
    public Result<String> save(ApplicationRecordDO applicationRecord) {
        applicationRecordService.insert(applicationRecord);
        return Result.ok();
    }

    @Log("修改应聘记录")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:applicationRecord:edit")
    public Result<String> update(ApplicationRecordDO applicationRecord) {
        boolean update = applicationRecordService.updateById(applicationRecord);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除应聘记录")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:applicationRecord:remove")
    public Result<String> remove(Long id) {
        applicationRecordService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除应聘记录")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:applicationRecord:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        applicationRecordService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }


    @Log("变更状态")
    @PostMapping( "/review")
    @ResponseBody
    @RequiresPermissions("jzweb:applicationRecord:review")
    public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state){
//        if (state.equals(0) || state.equals(1)) {

            //查询字典:消息模板
            DictDO dic = new DictDO();
            String valStr = "";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            int i = 0;
            for (Long id : ids) {
                ApplicationRecordDO applicationRecordDO = applicationRecordService.selectById(id);
                if(applicationRecordDO != null){
                    //查询机构名
                    OrganizationNewsDO org = organizationNewsService.selectById(applicationRecordDO.getOrgId());

                    //查询招聘信息
                    RecruitmentNewsDO rec = recruitmentNewsService.selectById(applicationRecordDO.getRnewsId());

                    MsgDO msg = new MsgDO();

                    applicationRecordDO.setState(state);
                    boolean b = applicationRecordService.updateById(applicationRecordDO);
                    if (b) {

                        //判断应聘是否成功
                        if (state == 0){
                            dic = dictService.findOneByKv("type" , "apply_yes");
                            msg.setTitle("岗位申请成功！");
                            valStr = dic.getValue();
                            valStr =  valStr.replace("{value1}" , org.getName());
                            valStr = valStr.replace("{value2}" , rec.getName());
                            valStr = valStr.replace("{value3}" , formatter.format(applicationRecordDO.getCreaterDate()));

                            msg.setContent(valStr);
                            msg.setUserId(applicationRecordDO.getUserId());
                            msg.setCreaterDate(new Date());
                            msg.setType(1);
                            msg.setMsgType(0);
                            msg.setState(0);
                            msg.setCreaterId(this.getUserId());
                            msgService.insert(msg);
                        }else if (state == 4){
                            msg.setTitle("您已上岗！");

                            msg.setContent("祝您工作愉快！");
                            msg.setUserId(applicationRecordDO.getUserId());
                            msg.setCreaterDate(new Date());
                            msg.setType(1);
                            msg.setMsgType(0);
                            msg.setState(0);
                            msg.setCreaterId(this.getUserId());
                            msgService.insert(msg);
                        }
                        i++;
                    } else {
                        break;
                    }
                }
            }
            if (i == ids.length) {
                return Result.build(0,"已成功变更：" + i + "条数据");
            } else {
                return Result.fail("变更状态修改失败！");
            }
    }

}
